#include "common.h"

int sockfd;
struct sockaddr_in addr;
short port = 1234;
char *ip = "127.0.0.1";

void init()
{
	sockfd = socket(PF_INET , SOCK_STREAM , 0);
	if(sockfd == -1)
		perror("socket") , exit(-1);
	addr.sin_family = PF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = inet_addr(ip);
	int res = connect(sockfd , (struct sockaddr *)&addr , sizeof(addr));
	if(res == -1)
		perror("connect") , exit(-1);
	printf("connect server successfully , start to communicate .\n");
	
	

}

void quit()
{
	printf("quit\n");
	close(sockfd);
	exit(0);
}

void* thread_recv(void* p)
{
	char mess[BUFSIZE] = {};
	while(1)
	{
		memset(mess , 0x00 , sizeof(mess));
		if(recv(sockfd,mess,sizeof(mess),0) <= 0)
		{
            		return;
        	}
        	printf("%s\n",mess);
	}
}

void start()
{
	//communicate
	char mess[BUFSIZE] = {};
	pthread_t id ;
	pthread_create(&id , 0 , thread_recv , 0);

	while(1)
	{
		memset(mess , 0x00 , sizeof(mess));
		scanf("%s",mess);
		send(sockfd , mess , sizeof(mess) , 0);
	}
	//pthread_join(id,0);
}

int main()
{	
	signal(SIGINT,quit);
	//1. initialize
	init();
	char name[20] = {};
	printf("input your name : ");
	scanf("%s",name);
	send(sockfd , name , strlen(name) , 0 );
	start();
	//3. close
	quit();
}
